package models

import (
	"ginstudydemo.com/main/dao"
)

type SysUserRole struct {
	UserID int64 `gorm:"column:user_id"`
	RoleID int64 `gorm:"column:role_id"`
}

// GetRoleIds 获取角色的ids
func GetRoleIds(userId string) (*[]int64, error) {
	var result []int64

	//SELECT role_id FROM sys_user_role WHERE user_id = ?
	err := dao.Db.Debug().Table("sys_user_role").
		Select("role_id").
		Where("user_id = ?", userId).
		Pluck("role_id", &result).Error

	if err != nil {
		return nil, err
	}
	return &result, nil
}

// GetUserRolesByUserID 根据用户id获取用户和角色所有对应数据
func GetUserRolesByUserID(userID string) ([]SysUserRole, error) {
	var userRoles []SysUserRole
	result := dao.Db.Debug().Table("sys_user_role").
		Where("user_id = ?", userID).Find(&userRoles)
	return userRoles, result.Error
}

// InsertUserRoles inserts user roles into the sys_user_role table,
// after checking for duplicates.
func InsertUserRoles(userID int64, roleIDs []int64) error {

	//先清空之前用户对应的角色
	if err := dao.Db.Table("sys_user_role").
		Where("user_id = ?", userID).
		Delete(&SysUserRole{}).Error; err != nil {
		return err
	}

	// 预置新的数据
	var rolesToInsert []SysUserRole
	for _, roleID := range roleIDs {
		rolesToInsert = append(rolesToInsert, SysUserRole{
			UserID: userID,
			RoleID: roleID,
		})
	}

	// Step 3: Insert non-duplicate roles
	if len(rolesToInsert) > 0 {
		if err := dao.Db.Table("sys_user_role").Create(&rolesToInsert).Error; err != nil {
			return err
		}
	}

	return nil
}
